//
//  TextFile.cpp
//  Editor
//
//  Created by Jeppe Nielsen on 10/22/14.
//  Copyright (c) 2014 Jeppe Nielsen. All rights reserved.
//

#include "TextFile.hpp"


void TextFile::Create(QTabWidget* tabs, QString filename) {
    
    tabWidget = tabs;
    
    
    QFont font;
    font.setFamily("Courier");
    font.setFixedPitch(true);
    font.setPointSize(14);
    
    textEditor = new QPlainTextEdit(tabs);
    textEditor->setFont(font);
    
    const int tabStop = 4;  // 4 characters

    QFontMetrics metrics(font);
    textEditor->setTabStopWidth(tabStop * metrics.width(' '));
    
    syntaxHighlighter.setDocument(textEditor->document());
    
    tabs->addTab(textEditor, "");
    
    ChangeFilename(filename);
    OpenTextFile();
}

bool TextFile::Close() {
    //QMessageBox::StandardButton reply = QMessageBox::warning(tabWidget, "Nano Editor", "Save changes before closing ?", QMessageBox::Yes, QMessageBox::No);
    
    
    
    int reply = 1;
    
    if (textEditor->document()->isModified()) {
        reply = QMessageBox::warning(tabWidget, "Nano Editor", "Save changes before closing?", "Yes", "No", "Cancel", 0, 2);
    }
    
    if (reply==0) {
        Save();
    }
    
    if (reply != 2) {
        tabWidget->removeTab(GetTabIndex());
        delete textEditor;
    }
    
    return reply != 2;
}

void TextFile::OpenTextFile() {
    QFile file(fileInfo.filePath());
   
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        textEditor->setPlainText(file.readAll());
    }
}

void TextFile::ChangeFilename(QString filename) {
    fileInfo.setFile(filename);
    tabWidget->setTabText(GetTabIndex(), fileInfo.fileName());
}

int TextFile::GetTabIndex() {
    return tabWidget->indexOf(textEditor);
}

void TextFile::Save() {
    QFile outputFile(fileInfo.filePath());
    outputFile.open(QIODevice::WriteOnly);
 
    /* Check it opened OK */
    if(!outputFile.isOpen()){
        qDebug() << "- Error, unable to save" << fileInfo.fileName();
        return;
    }
 
    /* Point a QTextStream object at the file */
    QTextStream outStream(&outputFile);
 
    /* Write the line to the file */
    outStream << textEditor->toPlainText();
 
    /* Close the file */
    outputFile.close();
    textEditor->document()->setModified(false);
}

QString TextFile::Path() {
    return fileInfo.filePath();
}

